/*
 * =====================================================================================
 *
 *       Filename:  results_in_database.cc
 *
 *    Description:  
 *
 *        Version:  1.0
 *        Created:  2013年07月16日 19时34分15秒
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  Xie Yanping (), 
 *        Company:  www.Qihoo.net
 *
 * =====================================================================================
 */

#include "results_in_database.h"
#include <algorithm>
#include "base/config_reader.h"
#include "database/scoped_connection.h"

namespace imlogs {

ResultsInDatabase::ResultsInDatabase()
    : database_pool_(NULL) {
  ConfigReader config("../conf/log_search_service.conf");
  database_pool_.reset(new base::SimpleConnectionPool(
          config.Get("database", "name").c_str(), config.Get("database", "server_list").c_str(),
          config.Get("database", "user").c_str(), config.Get("database", "password").c_str())
        );
}

ResultsInDatabase& ResultsInDatabase::GetInst() {
  static ResultsInDatabase sRetInDb;
  return sRetInDb;
}

int ResultsInDatabase::GetBreakStatistics(
    DialogueArray *dialogue_array,
    const std::string& date,
    int time/* = 600*/) {
  mysqlpp::ScopedConnection scoped_connection(*database_pool_);
  if (!scoped_connection)
    return -1;

  mysqlpp::Query sql_query(scoped_connection->query());
  std::string date_2_int_string = date;
  date_2_int_string.erase(std::remove_if(
        date_2_int_string.begin(),
        date_2_int_string.end(),
        std::bind2nd(std::equal_to<char>(), '-')),
        date_2_int_string.end());
  sql_query << "select * from message_analysis where date_of_msg=" << date_2_int_string;
  LOG_INFO("select analysis sql : " << sql_query.str());
  try {
    mysqlpp::UseQueryResult ret = sql_query.use();
    LOG_INFO("select recent_chated with result " << ret);
    if (ret) {
      while (mysqlpp::Row row = ret.fetch_row()) {
        (*dialogue_array).push_back(DialogueData());
        DialogueData& dd_ref = (*dialogue_array).back();
        dd_ref.sender_   = row["sender"];
        dd_ref.receiver_ = row["receiver"];
        dd_ref.time_     = row["time_of_first_msg"];
        dd_ref.count_    = row["count_of_msg"];
      }
    }
  } catch (mysqlpp::Exception& e) {
    LOG_ERROR(sql_query.str() << " exec error.(" << e.what() << ")");
    return -1;
  }

  return 0;
}

}
